const fs = require('fs');

// 上传单文件
const uploadSingle = (req, res) => {
	console.log(req.file);
	if (req.hasOwnProperty("file")) {
		res.send({ code: '200' });
	} else res.send({ code: '-1' });
}
// 上传
const uploadBase64 = async (req, res) => {
	// console.log(req.body);
	let { file, filename} = req.body;
	file = decodeURIComponent(file); // 转回base64
	file = file.replace(/^data:image\/\w+;base64,/, "") // 去除标识符
	file = Buffer.from(file, 'base64') // 转回字符流
	const result = await fs.writeFile(`./uploads/${filename}`, file, { flag: 'a+' }, err => {
		// if (err) return res.send({ code: '-1' });
		if (err) {
			console.log('上传错误：'+ err);
			return true
		}
	})
	if (result) return res.send({ code: '-1' });
	res.send({ code: '200' });
}
module.exports = { uploadSingle, uploadBase64 };